package com.easysettle

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Button
import android.widget.ImageButton
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.easysettle.model.CartItem
import com.easysettle.service.MainService
import java.text.SimpleDateFormat
import java.util.*

/**
 * 购物车Activity
 * 用于管理购物车中的商品和计算费用
 */
class ShoppingCartActivity : AppCompatActivity() {
    // UI组件
    private lateinit var recyclerViewCartItems: RecyclerView
    private lateinit var tvEmptyCartMessage: TextView
    private lateinit var progressBar: ProgressBar
    private lateinit var btnClearCart: Button
    private lateinit var btnCheckout: Button
    private lateinit var btnBack: ImageButton
    private lateinit var checkoutSummaryContainer: ViewGroup
    private lateinit var tvTotalQuantity: TextView
    private lateinit var tvTotalAmount: TextView
    
    // 主服务实例
    private lateinit var mainService: MainService
    // 购物车商品列表
    private lateinit var cartItems: MutableList<CartItem>
    // 购物车商品适配器
    private lateinit var cartAdapter: CartAdapter

    companion object {
        // 日志标签
        private const val TAG = "ShoppingCartActivity"
        // 结算结果请求码
        private const val CHECKOUT_RESULT_REQUEST = 106
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shopping_cart)
        
        // 初始化UI组件
        recyclerViewCartItems = findViewById(R.id.recycler_view_cart_items)
        tvEmptyCartMessage = findViewById(R.id.tv_empty_cart_message)
        progressBar = findViewById(R.id.progress_bar)
        btnClearCart = findViewById(R.id.btn_clear_cart)
        btnCheckout = findViewById(R.id.btn_checkout)
        btnBack = findViewById(R.id.btn_back)
        checkoutSummaryContainer = findViewById(R.id.checkout_summary_container)
        tvTotalQuantity = findViewById(R.id.tv_total_quantity)
        tvTotalAmount = findViewById(R.id.tv_total_amount)
        
        // 初始化主服务
        mainService = MainService(this)
        
        // 设置返回按钮点击事件
        btnBack.setOnClickListener { finish() }
        
        // 初始化RecyclerView
        recyclerViewCartItems.layoutManager = LinearLayoutManager(this)
        cartItems = mutableListOf()
        cartAdapter = CartAdapter(cartItems, this::onQuantityChange, this::onRemoveItem)
        recyclerViewCartItems.adapter = cartAdapter
        
        // 加载购物车数据
        loadCartItems()
        
        // 设置清空购物车按钮点击事件
        btnClearCart.setOnClickListener { clearShoppingCart() }
        
        // 设置结算按钮点击事件
        btnCheckout.setOnClickListener { checkout() }
    }

    /**
     * 加载购物车数据
     */
    private fun loadCartItems() {
        // 显示加载指示器
        progressBar.visibility = View.VISIBLE
        recyclerViewCartItems.visibility = View.GONE
        tvEmptyCartMessage.visibility = View.GONE
        
        mainService.getShoppingCartItems {
            items ->
            runOnUiThread {
                // 隐藏加载指示器
                progressBar.visibility = View.GONE
                
                cartItems.clear()
                if (items != null && items.isNotEmpty()) {
                    cartItems.addAll(items)
                    recyclerViewCartItems.visibility = View.VISIBLE
                    btnClearCart.visibility = View.VISIBLE
                    btnCheckout.visibility = View.VISIBLE
                    checkoutSummaryContainer.visibility = View.VISIBLE
                    cartAdapter.notifyDataSetChanged()
                    updateCheckoutSummary()
                } else {
                    tvEmptyCartMessage.visibility = View.VISIBLE
                    recyclerViewCartItems.visibility = View.GONE
                    btnClearCart.visibility = View.GONE
                    btnCheckout.visibility = View.GONE
                    checkoutSummaryContainer.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 更新结算摘要信息
     */
    private fun updateCheckoutSummary() {
        val totalQuantity = cartItems.sumOf { it.quantity }
        val totalAmount = cartItems.sumOf { it.getSubtotal() }
        
        tvTotalQuantity.text = String.format("%d", totalQuantity)
        tvTotalAmount.text = String.format("¥%.2f", totalAmount)
    }

    /**
     * 数量变化事件处理
     */
    private fun onQuantityChange(position: Int, newQuantity: Int) {
        if (newQuantity > 0) {
            // 更新商品数量
            val cartItem = cartItems[position]
            mainService.updateCartItemQuantity(cartItem.product.id, newQuantity) {
                success ->
                runOnUiThread {
                    if (success) {
                        cartItem.quantity = newQuantity
                        cartAdapter.notifyItemChanged(position)
                        updateCheckoutSummary()
                    } else {
                        Toast.makeText(this, "更新数量失败", Toast.LENGTH_SHORT).show()
                        cartAdapter.notifyItemChanged(position) // 恢复原有数量显示
                    }
                }
            }
        } else {
            // 数量为0，移除商品
            onRemoveItem(position)
        }
    }

    /**
     * 移除商品事件处理
     */
    private fun onRemoveItem(position: Int) {
        val cartItem = cartItems[position]
        mainService.removeFromCart(cartItem.product.id) {
            success ->
            runOnUiThread {
                if (success) {
                    cartItems.removeAt(position)
                    cartAdapter.notifyItemRemoved(position)
                    updateCheckoutSummary()
                    
                    // 如果购物车为空，更新界面显示
                    if (cartItems.isEmpty()) {
                        tvEmptyCartMessage.visibility = View.VISIBLE
                        recyclerViewCartItems.visibility = View.GONE
                        btnClearCart.visibility = View.GONE
                        btnCheckout.visibility = View.GONE
                        checkoutSummaryContainer.visibility = View.GONE
                    }
                } else {
                    Toast.makeText(this, "移除商品失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 清空购物车
     */
    private fun clearShoppingCart() {
        if (cartItems.isEmpty()) return
        
        // 显示确认对话框
        AlertDialog.Builder(this)
            .setTitle("清空购物车")
            .setMessage("确定要清空购物车吗？")
            .setPositiveButton("确定") {
                _, _ ->
                mainService.clearShoppingCart() {
                    success ->
                    runOnUiThread {
                        if (success) {
                            cartItems.clear()
                            cartAdapter.notifyDataSetChanged()
                            tvEmptyCartMessage.visibility = View.VISIBLE
                            recyclerViewCartItems.visibility = View.GONE
                            btnClearCart.visibility = View.GONE
                            btnCheckout.visibility = View.GONE
                            checkoutSummaryContainer.visibility = View.GONE
                            Toast.makeText(this, "购物车已清空", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(this, "清空购物车失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 结算购物车
     */
    private fun checkout() {
        if (cartItems.isEmpty()) return
        
        // 计算总金额
        val totalAmount = cartItems.sumOf { it.getSubtotal() }
        
        // 显示结算确认对话框
        AlertDialog.Builder(this)
            .setTitle("确认结算")
            .setMessage("共 ${cartItems.size} 件商品，合计: ¥${String.format("%.2f", totalAmount)}")
            .setPositiveButton("确认") {
                _, _ ->
                // 生成收据
                generateReceipt()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 生成收据
     */
    private fun generateReceipt() {
        // 生成收据号
        val receiptNumber = generateReceiptNumber()
        // 获取当前时间
        val receiptTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
        // 计算总金额
        val totalAmount = cartItems.sumOf { it.getSubtotal() }
        
        // 跳转到收据显示页面
        val intent = Intent(this, ReceiptActivity::class.java)
        intent.putExtra("receiptNumber", receiptNumber)
        intent.putExtra("receiptTime", receiptTime)
        intent.putExtra("totalAmount", totalAmount)
        intent.putExtra("cartItems", ArrayList(cartItems))
        startActivityForResult(intent, CHECKOUT_RESULT_REQUEST)
    }

    /**
     * 生成收据号
     */
    private fun generateReceiptNumber(): String {
        val dateFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        return "R-${dateFormat.format(Date())}"
    }

    /**
     * 处理结算结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        
        if (requestCode == CHECKOUT_RESULT_REQUEST && resultCode == RESULT_OK) {
            // 结算完成，清空购物车
            mainService.clearShoppingCart() {
                success ->
                runOnUiThread {
                    if (success) {
                        loadCartItems() // 重新加载购物车数据
                    }
                }
            }
        }
    }

    /**
     * 购物车商品适配器类
     */
    inner class CartAdapter(
        private val cartItems: List<CartItem>,
        private val onQuantityChange: (Int, Int) -> Unit,
        private val onRemoveItem: (Int) -> Unit
    ) : androidx.recyclerview.widget.RecyclerView.Adapter<CartAdapter.CartItemViewHolder>() {
        
        inner class CartItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
            val binding = com.easysettle.databinding.ItemCartBinding.bind(itemView)
        }
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartItemViewHolder {
            val view = layoutInflater.inflate(R.layout.item_cart, parent, false)
            return CartItemViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: CartItemViewHolder, position: Int) {
            val cartItem = cartItems[position]
            val product = cartItem.product
            
            // 显示商品信息
            holder.binding.tvProductName.text = product.name
            holder.binding.tvProductPrice.text = String.format("¥%.2f", product.price)
            holder.binding.tvQuantity.text = cartItem.quantity.toString()
            holder.binding.tvSubtotal.text = String.format("¥%.2f", cartItem.getSubtotal())
            
            // 设置减少数量按钮点击事件
            holder.binding.btnDecreaseQuantity.setOnClickListener {
                val newQuantity = cartItem.quantity - 1
                onQuantityChange(position, newQuantity)
            }
            
            // 设置增加数量按钮点击事件
            holder.binding.btnIncreaseQuantity.setOnClickListener {
                val newQuantity = cartItem.quantity + 1
                onQuantityChange(position, newQuantity)
            }
            
            // 设置删除按钮点击事件
            holder.binding.btnRemoveItem.setOnClickListener {
                onRemoveItem(position)
            }
        }
        
        override fun getItemCount(): Int {
            return cartItems.size
        }
    }
}